package com.mars.algorithm;

/**
 * @Author King
 * @create 2020/6/30 11:04
 */
public class KingArrayQueue<T> {

    private T[] data;
    private int size;
    private int n;
    private int head;
    private int tail;

    public KingArrayQueue(int capacity) {
        this.head = 0;
        this.tail = 0;
        this.data = (T[]) new Object[capacity];
        this.n = capacity;
    }

    public boolean enqueue(T d) {
        //队列满了
        if (head == 0 && tail == n) {
            return false;
        } else if (head != 0 && tail != n) {
            //做数据迁移，保证数据存储空间的连续性
            for (int i = head; i < tail; i++) {
                data[i - head] = data[i];
            }
            head = 0;
            tail = tail - head;
        }
        data[tail++] = d;
        size++;
        return true;
    }

    public T dequeue() {
        if (head == tail) {
            return null;
        }
        T t = data[head++];
        size--;
        return t;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        if (head == tail) {
            return true;
        }
        return false;
    }


    public static void main(String[] args) {
        KingArrayQueue<String> queue = new KingArrayQueue<String>(6);
        queue.enqueue("1");
        queue.enqueue("2");
        queue.enqueue("3");
        queue.enqueue("4");
        System.out.println(queue.dequeue());
        System.out.println(queue.dequeue());
        queue.enqueue("5");
        queue.enqueue("6");
    }

}
